<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Database\Model\Builder;

/**
 * 优惠券model
 *
 * @Author czm
 * @DateTime 2020-04-16
 */
class Coupon extends Model
{
    use SelectTrait;
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'coupon';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['batch_id','type','unique_num','status','share_time','get_time','use_time','last_time','openid','is_del','add_time'];
    protected $guarded=['id'];
    protected $hidden = ['is_del'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        // 'get_time'=>'datetime:Y-m-d H:i:s',
        // 'use_time'=>'datetime:Y-m-d H:i:s',
        'add_time'=>'datetime:Y-m-d H:i:s',
        'last_time'=>'datetime:Y-m-d H:i:s',
    ];
    // protected $appends = ['status_mapping'];

    const CREATED_AT = 'add_time';
    const UPDATED_AT = 'last_time';
    protected $dateFormat = 'U';

    protected function boot(): void
    {   
        $this->bootTraits();
        //model 软删除过滤 避免每次查询都添加is_del条件 去除条件添加withoutGlobalScope
        $this->addGlobalScope('is_del', function(Builder $builder) {
            $builder->where($this->table.'.is_del',1);
        });
        // var_dump($columns);
    }


    //筛选未使用券
    public function scopeOfNotUse($query)
    {
        return $query->where('status',1);
    }



    //映射状态 
    public function getStatusMappingAttribute(){
        
        switch($this->attributes['status']){
            case 0:$val='未领取';break;
            case 1:$val='未使用';break;
            case 2:$val='已使用';break;
            case 3:$val='已过期';break;
            case 4:$val='已禁用';break;
            case 5:$val='未生效';break;
            case 6:$val='已分享';break;
            default:$val='';break;
        }
        return $val;
    }


    public function couponBatch(){
       return  $this->belongsTo(CouponBatch::class,'batch_id','id');
    }

}